package com.jihu.design.behavioral.chain.ext;

import java.util.ArrayList;
import java.util.List;

/**
 * @author jihu
 * @date 2021/10/14
 */
public class FilterChain implements Filter {

    int cusor = 0;

    List<Filter> filtersChain = new ArrayList<>();

    //最终要执行的目标方法
    My target;

    public FilterChain setTarget(My target) {
        this.target = target;
        return this;
    }

    public My getTarget() {
        return target;
    }

    void addFilter(Filter filter){
        filtersChain.add(filter);
    }

    @Override
    public void doFilter(Request request, Response response, FilterChain chain) {
        //第一次执行第一个filter
        if(cusor < filtersChain.size()){
            Filter filter = filtersChain.get(cusor);
            cusor++;
            filter.doFilter(request,response,chain);
        } else {
            //filter完了，该执行目标方法了
            target.hello();
        }


    }
}
